import 'package:app_core/app_core.dart';
import 'package:flutter/material.dart';
import 'package:yh_core_flutter_project/project/common/channels/index.dart';

/// Flutter与iOS原生通信测试页面
/// 测试数据通信、页面交互、第三方插件等功能
class ChannelTestPage extends StatefulWidget {
  const ChannelTestPage({super.key});

  @override
  State<ChannelTestPage> createState() => _ChannelTestPageState();
}

class _ChannelTestPageState extends State<ChannelTestPage> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _ageController = TextEditingController();

  String _lastResponse = '暂无响应';

  @override
  void initState() {
    super.initState();
    _nameController.text = '我是flutter的张三';
    _emailController.text = 'zhangsan@example.com';
    _ageController.text = '25';

    _setDataChannelHandler();
  }

  /// 处理原生端端主动返回数据处理
  void _setDataChannelHandler() {
    DataChannel.setDataChannelHandler(
      (data) => {
        setState(() {
          _lastResponse = '✅ 发送成功！\n${_formatResponse(data)}';
        }),
      },
    );

    /// 数据事件流监听
    DataEventChannel.nativeDataStream.listen((onData) {
      print('收到原生端数据流: $onData');
      setState(() {
        _lastResponse = '✅ 发送成功！\n${_formatResponse(onData)}';
      });
    });
  }

  @override
  void dispose() {
    _nameController.dispose();
    _emailController.dispose();
    _ageController.dispose();
    super.dispose();
  }

  /// 发送用户信息给iOS
  Future<void> _sendUserInfo() async {
    if (_nameController.text.isEmpty || _emailController.text.isEmpty || _ageController.text.isEmpty) {
      _showSnackBar('请填写完整的用户信息');
      return;
    }

    setState(() {
      _lastResponse = '正在发送用户信息...';
    });

    try {
      final userInfo = {
        'name': _nameController.text,
        'email': _emailController.text,
        'age': int.tryParse(_ageController.text) ?? 0,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
      };
      final response = await DataChannel.sendUserInfo(userInfo);
      setState(() {
        _lastResponse = '✅ 发送成功！\n${_formatResponse(response)}';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 发送失败: $e';
      });
    }
  }

  /// 获取设备信息
  Future<void> _getDeviceInfo() async {
    setState(() {
      _lastResponse = '正在获取设备信息...';
    });
    try {
      final response = await DataChannel.getDeviceInfo();
      setState(() {
        _lastResponse = '✅ 获取成功！\n${_formatResponse(response)}';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 获取失败: $e';
      });
    }
  }

  /// 打开页面A
  Future<void> _openPageA() async {
    if (_nameController.text.isEmpty || _emailController.text.isEmpty || _ageController.text.isEmpty) {
      _showSnackBar('请填写完整的用户信息');
      return;
    }

    setState(() {
      _lastResponse = '正在打开页面A...';
    });

    try {
      final userInfo = {
        'name': _nameController.text,
        'email': _emailController.text,
        'age': int.tryParse(_ageController.text) ?? 0,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
      };

      final result = await NavigationChannel.openPageA(userInfo);
      setState(() {
        _lastResponse = result ? '✅ 页面A打开成功！' : '❌ 页面A打开失败';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 打开页面A失败: $e';
      });
    }
  }

  /// 谷歌登录
  Future<void> _googleLogin() async {
    setState(() {
      _lastResponse = '正在调用iOS谷歌登录...';
    });

    try {
      final response = await PluginChannel.googleLogin();
      setState(() {
        _lastResponse = '✅ 谷歌登录成功！\n${_formatResponse(response)}';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 谷歌登录失败: $e';
      });
    }
  }

  /// 微信登录
  Future<void> _wechatLogin() async {
    setState(() {
      _lastResponse = '正在调用iOS微信登录...';
    });
    try {
      final response = await PluginChannel.wechatLogin();
      setState(() {
        _lastResponse = '✅ 微信登录成功！\n${_formatResponse(response)}';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 微信登录失败: $e';
      });
    }
  }

  /// 支付宝支付
  Future<void> _alipayPayment() async {
    setState(() {
      _lastResponse = '正在调用iOS支付宝支付...';
    });
    try {
      final response = await PluginChannel.alipayPayment(orderId: 'ORDER_${DateTime.now().millisecondsSinceEpoch}', amount: 99.99);
      setState(() {
        _lastResponse = '✅ 支付宝支付成功！\n${_formatResponse(response)}';
      });
    } catch (e) {
      setState(() {
        _lastResponse = '❌ 支付宝支付失败: $e';
      });
    }
  }

  /// 格式化响应数据
  String _formatResponse(Map<String, dynamic> response) {
    return response.entries.map((e) => '${e.key}: ${e.value}').join('\n');
  }

  /// 显示提示信息
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar('Flutter-iOS通信测试'),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('用户信息', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    TextField(controller: _nameController, decoration: const InputDecoration(labelText: '姓名', border: OutlineInputBorder())),
                    const SizedBox(height: 12),
                    TextField(controller: _emailController, decoration: const InputDecoration(labelText: '邮箱', border: OutlineInputBorder())),
                    const SizedBox(height: 12),
                    TextField(
                      controller: _ageController,
                      decoration: const InputDecoration(labelText: '年龄', border: OutlineInputBorder()),
                      keyboardType: TextInputType.number,
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('数据通信', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _sendUserInfo,
                            style: ElevatedButton.styleFrom(backgroundColor: Colors.green, foregroundColor: Colors.white),
                            child: const Text('发送用户信息'),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _getDeviceInfo,
                            style: ElevatedButton.styleFrom(backgroundColor: Colors.blue, foregroundColor: Colors.white),
                            child: const Text('获取设备信息'),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('页面交互', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _openPageA,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.orange,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                        ),
                        child: const Text('打开页面A（传入用户信息）'),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('第三方插件', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _googleLogin,
                            style: ElevatedButton.styleFrom(backgroundColor: Colors.red, foregroundColor: Colors.white),
                            child: const Text('谷歌登录'),
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _wechatLogin,
                            style: ElevatedButton.styleFrom(backgroundColor: Colors.green, foregroundColor: Colors.white),
                            child: const Text('微信登录'),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: _alipayPayment,
                        style: ElevatedButton.styleFrom(backgroundColor: Colors.blue, foregroundColor: Colors.white),
                        child: const Text('支付宝支付'),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),

            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('iOS响应结果', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 12),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(color: Colors.grey[100], borderRadius: BorderRadius.circular(8), border: Border.all(color: Colors.grey[300]!)),
                      child: SingleChildScrollView(child: Text(_lastResponse, style: const TextStyle(fontSize: 14, fontFamily: 'monospace'))),
                    ),
                  ],
                ),
              ),
            ),

            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }
}
